package com.ktjiaoyu.server.config.security;

import com.ktjiaoyu.server.pojo.Menu;
import com.ktjiaoyu.server.pojo.Role;
import com.ktjiaoyu.server.service.IMenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    @Resource
    IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //1.获取用户请求的路劲
        String url = ((FilterInvocation) o).getRequestUrl();
        //2.判断该路劲是否需要保护
        List<Menu> menus = menuService.getMenusWithRole();
        for (Menu menu : menus) {
            //如果需要；查询那些角色可以访问
            if(antPathMatcher.match(menu.getUrl(),url)){
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                // 再把角色名数组通过createList()方法存放list中
                return org.springframework.security.access.SecurityConfig.createList(str);
            }
        }
        //如果不需要：说明只要登录即可访问
        // 没匹配的url默认登录即可访问(默认给用户一个用于登录的角色)
        return org.springframework.security.access.SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
